import TIM from "@/utils/tim-js-friendship.js";
import TIMUploadPlugin from "tim-upload-plugin";
import { flushFriendList } from "@/utils/im-api/friendManager.js";
import { loginSuccess, logoutSuccess } from "@/utils/im-api/loginManager.js";
import { historyUpdateFlag } from "@/utils/im-api/historySession";
import { flushGroupList } from "@/utils/im-api/groupManager.js";
import store from "@/store/index.js";

// 初始化 SDK 实例

var SDK_READ_STATUS = false;

const tim = TIM.create({
  SDKAppID: 1400577099
});

window.setLogLevel = tim.setLogLevel;

// 无日志级别
tim.setLogLevel(1);

// 注册 cos
tim.registerPlugin({ "tim-upload-plugin": TIMUploadPlugin });

/**
 * 对事件进行监听
 */

/**
 * sdk处于ready状态触发,这个只有用户登录成功的时候触发
 */
tim.on(TIM.EVENT.SDK_READY, async () => {
  SDK_READ_STATUS = true;

  console.log("tim 登录回调");

  //获取登录用户的资料
  await loginSuccess(); //获取用户列表
  await flushFriendList();
  await flushGroupList();
});

//对方读取消息 只支持 单聊 c2c
tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, async () => {
  await historyUpdateFlag(true);
});

//用户的好友列表改变触发事件
tim.on(TIM.EVENT.FRIEND_LIST_UPDATED, async () => {
  await flushFriendList();
});

/**
 * 退出登录 清理数据的操作
 */
tim.on(TIM.EVENT.SDK_NOT_READY, async () => {
  await logoutSuccess();
});

/**
 * 会话列表更新事件
 */
tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, async data => {
  //会话列表
  if (data && data.name === "onConversationListUpdated" && data.data) {
    store.commit("imStore/RESET_CONVERSATIONLIST", data.data || []);
  }
});

/**
 * 收到消息
 */
tim.on(TIM.EVENT.MESSAGE_RECEIVED, async message => {
  //刷新页面获取消息
  await historyUpdateFlag(true);
});

//群组列表更新
tim.on(TIM.EVENT.GROUP_LIST_UPDATED, async message => {
  //await flushGroupList();
});
export default tim;
